package com.crm.web.page;

import org.apache.tapestry.IPage;
import org.apache.tapestry.valid.ValidationDelegate;
import org.apache.tapestry.valid.ValidationConstraint;
import org.apache.tapestry.event.PageBeginRenderListener;
import org.apache.tapestry.event.PageEvent;
import org.apache.tapestry.html.BasePage;
import org.apache.tapestry.annotations.InjectState;
import org.apache.tapestry.annotations.InjectPage;
import org.apache.tapestry.annotations.Bean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.List;
import java.util.ArrayList;

import com.crm.model.User;
import com.crm.service.IProcessService;
import com.crm.service.IUserService;
import com.javaforge.tapestry.spring.annotations.InjectSpring;

/**
 * @author <a href="mailto:huang0510@hotmail.com">HuangHuang</a>
 * @version $Id$
 */
public abstract class UserList extends BasePage implements PageBeginRenderListener {
    
    private static Log log = LogFactory.getLog(UserList.class);
    private int count;

    /** 控制业务负责人列表是否显示 */
    private boolean showFieldset;

    @InjectSpring("processService")
    public abstract IProcessService getProcessService();

    @InjectSpring("userService")
    public abstract IUserService getUserService();

    @InjectState("userSession")
    public abstract User getUserSession();

    @InjectPage("ProcessHistory")
    public abstract ProcessHistory getProcessHistoryPage();

    @Bean
    public abstract ValidationDelegate getDelegate();

    public void setShowFieldset(boolean showFieldset) {
        this.showFieldset = showFieldset;
    }

    public boolean getShowFieldset() {
        return showFieldset;
    }

    public String getRecordCount() {
        return "共" + count + "条记录";
    }

    public IPage onShowDetails() {
        return getProcessHistoryPage();
    }

    public void pageBeginRender(PageEvent event) {
        if (getUserSession().getUsername() == null) {
            event.getRequestCycle().sendRedirect("app?page=SysPageError&service=page");
        }

        setShowFieldset(true);
        if (getUserSession().getUserGroup().equals(User.GROUP_SUPER)) {
            event.getRequestCycle().sendRedirect("app?page=ProcessHistory&service=page");
        }
    }

    public List getEntries() {
        try {
            List list = getUserService().getUserByGroup(getUserSession().getUserGroup());
            count = list.size();
            return list;
        }
        catch (Exception e) {
            String exceptionString = "The exception happened when list user information. " + e.getMessage();
            log.warn(exceptionString);
            e.printStackTrace();
            getDelegate().record(exceptionString, ValidationConstraint.CONSISTENCY);
            return new ArrayList();
        }
    }
}
